package com.wc5818.wcSysUser.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wc5818.common.AjaxResult;
import com.wc5818.sysDictData.entity.SysDictData;
import com.wc5818.sysDictData.mapper.SysDictDataMapper;
import com.wc5818.wcSysUser.dto.Jscode2session;
import com.wc5818.wcSysUser.dto.StatisGroupByYewLevel;
import com.wc5818.wcSysUser.dto.WcSysUserEx;
import com.wc5818.wcSysUser.entity.WcSysUser;
import com.wc5818.wcSysUser.mapper.WcSysUserMapper;
import com.wc5818.wcSysUser.service.IWcSysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-02-15
 */
@RestController
@RequestMapping("/wcSysUser")
public class WcSysUserController {

    @Value("${weixin.appId}")
    String _appId = "";

    @Value("${weixin.secret}")
    String _secret = "";

    @Autowired
    WcSysUserMapper wcSysUserMapper;

    @Autowired
    SysDictDataMapper sysDictDataMapper;

    @Autowired
    RestTemplate restTemplate;

    // 我的里面，点击头像更新微信信息; 没注册前用户点击还没有userId。所以用openid做查询条件
    @PostMapping("/updateByOpenId")
    public Object updateByOpenId(@RequestBody WcSysUser wcSysUser) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(false);
        List<WcSysUser> list = wcSysUserMapper.selectList(new QueryWrapper<WcSysUser>().eq("openId", wcSysUser.getOpenId()));
        if(list != null && list.size() > 0) {
            int rtn = wcSysUserMapper.update(wcSysUser, new QueryWrapper<WcSysUser>().eq("openId", wcSysUser.getOpenId()));
            if (rtn >= 0) {
                WcSysUser wcSysUser2 = list.get(0);
                wcSysUser2.setNickName(wcSysUser.getNickName());
                wcSysUser2.setAvatarUrl(wcSysUser.getAvatarUrl());

                WcSysUserEx wcSysUserEx = new WcSysUserEx();
                BeanUtils.copyProperties(wcSysUser2, wcSysUserEx);
                fillUserNameById(wcSysUserEx);
                fillDictValueByDataCode(wcSysUserEx);

                ajaxResult.setSuccess(true);
                ajaxResult.setData(wcSysUserEx);
            }
        }

        return ajaxResult;
    }

    // 统计我的页面需要的那些数
    @GetMapping("/statistics")
    public Object statistics(String userId) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(false);

        // 造假基数
//        int factor = 0;
//        WcSysUser wcSysUser = wcSysUserMapper.selectById(userId);
//        if(wcSysUser != null && wcSysUser.getFactor() != null)
//            factor = wcSysUser.getFactor();

        Map<String, Object> map = new HashMap<>();

        List<StatisGroupByYewLevel> list = wcSysUserMapper.groupByYewLevel(userId);
//        for (StatisGroupByYewLevel statisGroupByYewLevel: list
//        ) {
//            int src = statisGroupByYewLevel.getAmount();
//            statisGroupByYewLevel.setAmount(src + new Random().nextInt(factor));
//        }

        int all = 0;
        for (StatisGroupByYewLevel statisGroupByYewLevel: list
             ) {
            all += statisGroupByYewLevel.getAmount();
            map.put("_" + statisGroupByYewLevel.getYewLevel(), statisGroupByYewLevel.getAmount());
        }

        map.put("all", all);

        ajaxResult.setSuccess(true);
        ajaxResult.setData(map);

        return ajaxResult;
    }

    void fillUserNameById(WcSysUserEx wcSysUserEx) {
        WcSysUser wcSysUser = wcSysUserMapper.selectById(wcSysUserEx.getParentUserId());
        if (wcSysUser != null) {
            wcSysUserEx.setFatherName(wcSysUser.getRealName());
        }
    }

    void fillDictValueByDataCode(WcSysUserEx wcSysUserEx) {
        SysDictData sysDictData = sysDictDataMapper.selectOne(new QueryWrapper<SysDictData>().eq("dict_code", wcSysUserEx.getForsysuserId()));

        if (sysDictData != null) {
            wcSysUserEx.setLevelName(sysDictData.getDictLabel());
        }
    }

    // 通过微信登录code获取openid，在用openid查用户表。返回用户对象
    @GetMapping("/getUserByWxLoginCode")
    public Object getUserByWxLoginCode(String code) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(false);

        WcSysUserEx wcSysUserEx = new WcSysUserEx();

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="
                + _appId + "&secret=" + _secret + "&js_code=" + code + "&grant_type=authorization_code";

        Jscode2session jscode2session = restTemplate.getForObject(url, Jscode2session.class);
        if (jscode2session.getOpenid() != null) {
            List<WcSysUser> list = wcSysUserMapper.selectList(new QueryWrapper<WcSysUser>().eq("openId", jscode2session.getOpenid()));
            if (list != null && list.size() > 0) {
                ajaxResult.setSuccess(true);
                wcSysUserEx = new WcSysUserEx();
                BeanUtils.copyProperties(list.get(0), wcSysUserEx);
                fillUserNameById(wcSysUserEx);
                fillDictValueByDataCode(wcSysUserEx);

                ajaxResult.setData(wcSysUserEx);
                return ajaxResult;

            } else {
                wcSysUserEx = new WcSysUserEx();
                wcSysUserEx.setOpenId(jscode2session.getOpenid());
                ajaxResult.setData(wcSysUserEx);
            }
        }

        return ajaxResult;
    }

    // 注册用户绑定openid
    @PostMapping("/addUser")
    public Object addUser(@RequestBody WcSysUser wcSysUser) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(false);

        List list = wcSysUserMapper.selectList(new QueryWrapper<WcSysUser>().eq("openId", wcSysUser.getOpenId()));
        if(list != null && list.size() > 0) {
            ajaxResult.setErrorMsg("这个微信已经注册过了!");
            return ajaxResult;
        }

        wcSysUser.setCreateTime(LocalDateTime.now());
        wcSysUser.setUpdateTime(LocalDateTime.now());

        if (wcSysUserMapper.insert(wcSysUser) > 0) {
            ajaxResult.setSuccess(true);
            ajaxResult.setData(wcSysUser);
        }

        return ajaxResult;
    }

    @GetMapping("/getParentUserId")
    public Object getParentUserId(Integer userId) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(false);

        List<WcSysUser> list = wcSysUserMapper.selectList(new QueryWrapper<WcSysUser>().eq("parentUserId", userId));
        if (list != null && list.size() > 0) {
            ajaxResult.setSuccess(true);
            List<WcSysUserEx> wcSysUserExs = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                WcSysUserEx wcSysUserEx = new WcSysUserEx();
                BeanUtils.copyProperties(list.get(i), wcSysUserEx);
                fillUserNameById(wcSysUserEx);
                fillDictValueByDataCode(wcSysUserEx);
                wcSysUserExs.add(wcSysUserEx);
            }

            ajaxResult.setData(wcSysUserExs);
            return ajaxResult;
        }

        return ajaxResult;
    }

    // 用手机号查用户对象
    @GetMapping("/queryUserByMobile")
    public Object queryUserByMobile(String mobile) {
        AjaxResult ajaxResult = new AjaxResult();
        ajaxResult.setSuccess(false);

        List<WcSysUser> list = wcSysUserMapper.selectList(new QueryWrapper<WcSysUser>().eq("mobile", mobile));
        if (list != null && list.size() > 0) {
            ajaxResult.setSuccess(true);
            ajaxResult.setData(list.get(0));
            return ajaxResult;
        }

        return ajaxResult;
    }

}
